package com.pan.service;

import com.pan.constants.DatabaseInfo;
import com.pan.dao.User;
import com.pan.dao.UserDAO;
import com.pan.dao.UserDAOImpl;
import com.pan.util.TokenGenerator;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.concurrent.TimeUnit;

@WebServlet("/register")
public class Register extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("userName");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        // 以当前时间戳作为文件存储路径
        String filePath = String.valueOf(System.currentTimeMillis());
        File file = new File(DatabaseInfo.FILE_PATH + "\\" + filePath);
        file.mkdir();
        UserDAO userDAO = UserDAOImpl.getInstance();
        JSONObject jsonResponse = new JSONObject();
        boolean success = false;
        String message = "注册失败";
        String token = null;
        try {
            if (userDAO.addUser(new User(username, password, email, filePath))) {
                // 获取新注册的用户信息
                User newUser = userDAO.getUserByEmail(email);
                if (newUser != null) {
                    // 生成Token及过期时间（7天后）
                    token = TokenGenerator.generateToken();
                    long expiryMillis = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(7);
                    Timestamp expiry = new Timestamp(expiryMillis);

                    // 保存Token到数据库
                    try {
                        userDAO.saveToken(newUser.getId(), token, expiry);
                        // 重新获取用户确保Token更新
                        User updatedUser = userDAO.getUserById(newUser.getId());
                        token = updatedUser.getToken();
                    } catch (SQLException e) {
                        e.printStackTrace();
                        message = "令牌生成失败";
                    }
                    success = true;
                    message = "注册成功";
                } else {
                    message = "注册失败，用户信息未找到";
                }
            } else {
                message = "注册失败，邮箱已存在";
            }
        } catch (SQLException e) {
            message = "数据库错误";
            e.printStackTrace();
        }
        // 构造JSON响应
        jsonResponse.put("status", success ? "success" : "error");
        jsonResponse.put("message", message);
        if (success) {
            jsonResponse.put("token", token);
        } else {
            jsonResponse.put("token", JSONObject.NULL);
        }

        // 设置响应头并输出
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.print(jsonResponse.toString());
        out.flush();
        out.close();
    }
}
